<template>
  <div class="report-card flex">
    <ul class="nav">
      <li v-for="(val, key) in infoMap" :key="key" :class="{'active': activeCatalog === key}" @click="goAnchor(key)">{{ key }}</li>
    </ul>
    <div class="box-container">
      <el-form label-width="100px" class="report-form" @scroll.native="handleScroll">
        <div v-for="(val, key) in infoMap" :key="key" class="box">
          <div :class="['title', key]">{{ key }}</div>
          <div class="content">
            <div v-for="item in val" :key="item.id">
              <el-form-item label="核查内容" class="check-item">
                {{ item.content }}
              </el-form-item>

              <el-form-item v-if="key === '较大以上安全风险信息' && basicInfo.bigRiskInfoList && basicInfo.bigRiskInfoList.length && item.fieldName !== 'bigRiskStatus'" label="安全风险信息">
                <div class="table">
                  <div class="table-row">
                    <div v-if="item.fieldName === 'riskCode'" class="cell">风险代码</div>
                    <div class="cell">风险名称</div>
                    <div v-if="item.fieldName === 'riskPosition'" class="cell">风险所在位置</div>
                    <div v-if="item.fieldName === 'riskPoint'" class="cell">风险点</div>
                  </div>
                  <div v-for="risk in basicInfo.bigRiskInfoList" :key="risk.riskCode" class="table-row">
                    <div v-if="item.fieldName === 'riskCode'" class="cell">{{ risk.riskCode }}</div>
                    <div class="cell">{{ risk.riskName }}</div>
                    <div v-if="item.fieldName === 'riskPosition'" class="cell">{{ risk.riskPosition }}</div>
                    <div v-if="item.fieldName === 'riskPoint'" class="cell">{{ risk.riskPoint }}</div>
                  </div>
                </div>
              </el-form-item>

              <el-form-item label="核查结果">
                <el-select
                  v-model="item.result"
                  :disabled="status === 2 && !isEditing"
                  placeholder="请选择"
                  class="input"
                  @change="handleChange"
                >
                  <el-option
                    v-for="dict in dict.type.env_system_yes_no"
                    :key="dict.value"
                    :label="dict.label"
                    :value="dict.value"
                  />
                </el-select>
              </el-form-item>

              <el-form-item label="建议">
                <el-input
                  v-model="item.advice"
                  :disabled="status === 2 && !isEditing"
                  type="textarea"
                  class="input"
                  placeholder="请输入内容"
                  @change="handleChange"
                />
              </el-form-item>
              <el-form-item label="附件">
                <el-upload
                  list-type="picture-card"
                  action="#"
                  multiple
                  class="input"
                  :disabled="status === 2 && !isEditing"
                  :file-list="item.fileList"
                  :auto-upload="false"
                  :on-preview="previewFile"
                  :before-remove="beforeRemoveFile"
                  :on-remove="(file, fileList) => deleteFile(item, file, fileList)"
                  :on-change="(file) => addFile(item, file)"
                >
                  <i class="el-icon-plus" />
                </el-upload>
              </el-form-item>
            </div>
          </div>
        </div>
      </el-form>

      <div v-if="status !== -1" class="footer">
        <div v-if="status !== 2" class="btn cancel" @click="onCancel">取消</div>
        <div v-if="status === 0" class="btn confirm" @click="onStart">启动</div>
        <div v-if="status === 1" class="btn confirm" @click="onConfirm">暂存</div>
        <div v-if="status === 1" class="btn submit" @click="onSubmit">完成</div>
        <div v-if="status === 1" class="btn terminate" @click="onTerminate">终止</div>
        <template v-if="status === 2 && isAdmin">
          <div v-if="isEditing" class="btn cancel" @click="onCorrectCancel">取消</div>
          <div class="btn confirm" @click="onCorrect">更正</div>
        </template>
        <template v-if="status === 2">
          <div class="btn submit" @click="onExport('promise')">导出安全承诺书</div>
          <div class="btn submit" @click="onExport('check')">导出核查表</div>
        </template>
      </div>
    </div>

    <el-dialog :visible.sync="dialogVisible" append-to-body>
      <img width="100%" :src="dialogImageUrl" alt="">
    </el-dialog>
  </div>
</template>
<script>
import { saveAs } from 'file-saver'
import { isImage } from '@/utils'
import { deleteFile } from '@/api/system/file'

export default {
  name: 'SecReportCard',
  dicts: ['env_system_yes_no'],
  props: {
    basicInfo: {
      type: Object,
      required: true
    },
    reportInfo: {
      type: Array,
      required: true
    },
    isAdmin: Boolean,
    status: {
      type: Number,
      default: -1
    }
  },
  data() {
    return {
      infoMap: {},
      formData: [], // 提交时的数据
      anchorOffsetMap: {},
      activeCatalog: '',

      showPicker: false,
      pickerType: 'select',
      pickerKey: null,
      pickerId: null,
      options: [],

      isEditing: false,
      dialogVisible: false,
      dialogImageUrl: ''
    }
  },
  watch: {
    reportInfo: {
      immediate: true,
      handler: function(val) {
        val && this.initData()
      }
    }
  },
  methods: {
    // 初始化anchor高度
    initAnchorData() {
      for (const key in this.infoMap) {
        this.anchorOffsetMap[key] = document.querySelector(`.${key}`) ? document.querySelector(`.${key}`).offsetTop : 0
      }
    },

    goAnchor(catalog) {
      this.clicked = true
      this.activeCatalog = catalog
      const el = document.querySelector('.report-form')
      el.scrollTo({
        top: this.anchorOffsetMap[catalog] - 5,
        behavior: 'smooth'
      })
    },
    handleScroll(e) {
      const top = e.target.scrollTop
      let active = null
      for (const key in this.infoMap) {
        if (top + 100 >= this.anchorOffsetMap[key]) {
          active = key
        }
      }
      if (this.clicked) {
        setTimeout(() => { this.clicked = false }, 1100)
      } else {
        this.activeCatalog = active
      }
    },
    initData() {
      const obj = {}
      this.reportInfo.forEach(item => {
        obj[item.classType] = obj[item.classType] || []
        obj[item.classType].push(item)
      })
      this.infoMap = obj
      this.activeCatalog = Object.keys(obj)[0]
      setTimeout(this.initAnchorData, 100)
    },
    handleChange() {
      this.$emit('input', this.reportInfo)
      this.$emit('change', this.reportInfo)
    },
    beforeRemoveFile(file) {
      return new Promise((resolve, reject) => {
        this.$modal.confirm(`确认删除？`).then(function() {
          resolve()
        }).catch(() => {
          reject()
        })
      })
    },
    async deleteFile(item, file, fileList) {
      if (file.id) {
        await deleteFile(file.id)
      }
      item.fileList = fileList
      this.handleChange()
    },
    addFile(item, file) {
      item.fileList.push(file)
      this.handleChange()
    },
    getFileBlobUrl(file) {
      if (window.createObjectURL) {
        return window.createObjectURL(file)
      } else if (window.URL) {
        return window.URL.createObjectURL(file)
      } else if (window.webkitURL) {
        return window.webkitURL.createObjectURL(file)
      }
    },
    previewFile(file) {
      if (file.raw) {
        if (file.raw.type.includes('image')) {
          const url = this.getFileBlobUrl(file.raw)
          this.dialogImageUrl = url
          this.dialogVisible = true
        } else {
          saveAs(file.raw)
        }
      } else if (isImage(file.url.split('.').pop())) {
        this.dialogImageUrl = file.url
        this.dialogVisible = true
      } else {
        saveAs(file.url)
      }
    },

    onCancel() {
      this.$router.back()
    },
    onStart() {
      this.$emit('start')
    },
    onTerminate() {
      this.$emit('terminate')
    },
    onCorrectCancel() {
      this.isEditing = false
    },
    onCorrect() {
      if (this.isEditing) {
        this.isEditing = false
        this.$emit('correct', {
          type: 'sec-report',
          formData: this.reportInfo
        })
      } else {
        this.isEditing = true
      }
    },
    // 保存
    onConfirm() {
      this.$emit('confirm', {
        type: 'sec-report',
        formData: this.reportInfo
      })
    },
    onSubmit() {
      this.$emit('submit', {
        type: 'sec-report',
        formData: this.reportInfo
      })
    },
    onExport(type) {
      this.$emit('export', type)
    }
  }
}
</script>
<style lang="scss" scoped>
@import "~@/assets/styles/variables.scss";

.report-card {
  height: 100%;
  overflow: hidden;
  background-color: #fff;
}
ul {
  list-style: none;
  margin: 0;
  padding: 0;
  border-right: 1px solid $border-color;
  overflow: auto;
  li {
      padding: 10px 12px;
      white-space: nowrap;
      cursor: pointer;
      &.active {
        color: $primary-color;
        border-left: 3px $primary-color;
        box-shadow: -1px 0 $primary-color;
      }
    }
}
.box-container {
  display: flex;
  flex-direction: column;
  flex-grow: 2;
  padding-top: 10px;
}
.report-form {
  margin-left: 20px;
  flex-grow: 2;
  overflow: auto;
}

.box {
  .title {
    position: relative;
    font-size: 14px;
    color: $label-color;
    line-height: 26px;
    padding-left: 10px;
    margin: 0 0 10px;
    text-align: initial;
    &::before {
      content: '';
      position: absolute;
      left: 0;
      top: 3px;
      bottom: 0;
      width: 3px;
      background-color: $primary-color;
      border-radius: 3px;
    }
  }
}
.check-item {
  color: $warning-color;
}

.table {
  width: 600px;
  border-top: 1px solid $border-color;
  border-left: 1px solid $border-color;
  .table-row {
    display: flex;
    border-bottom: 1px solid $border-color;
    &:first-child {
      background-color: $background-color;
      color: $text-color-light;
      .cell {
        font-size: 12px;
      }
    }
  }
  .cell {
    padding: 3px 10px;
    width: 50%;
    border-right: 1px solid $border-color;
  }
}
</style>
